package org.ne.springboot.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.xwpf.usermodel.IBodyElement;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.ne.springboot.service.TableCheckService;
import org.ne.springboot.utils.PaperHandleUtils.CommonUtils.WordUtils;
import org.ne.springboot.utils.PaperHandleUtils.PaperContentCheckUtils.SparkClient;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author luolinila
 * @date 2025/9/3 22:00
 */
@Service
public class TableFormatServiceImpl implements TableCheckService {
    @Override
    public List<String> checkTableTitle(XWPFDocument document) {
        try (document) {


            List<String> headings = WordUtils.findHeadingOne(document);

            // 获取文档中的所有主体元素（段落和表格）
            List<IBodyElement> bodyElements = document.getBodyElements();

            // 用于存储找到的表格及其对应的表名
            List<XWPFParagraph> tablesWithTitles = new ArrayList<>();
            List<String>  correctTableNumbering = new ArrayList<>();
            int a = 0, b = 0;

            // 遍历所有元素
            for (int i = 0; i < bodyElements.size(); i++) {
                IBodyElement element = bodyElements.get(i);

                // 如果当前元素是表格
                if (element instanceof XWPFTable) {
                    b++;
                    // 回溯查找表名
                    if(i > 0) {
                        XWPFParagraph para = (XWPFParagraph) bodyElements.get(i - 1);
                        tablesWithTitles.add(para);
                        correctTableNumbering.add("表" + a + "." + b);
                    }
                }else if (element instanceof XWPFParagraph) {
                    String text = ((XWPFParagraph) element).getText();
                    if(headings.contains(text.trim())) {
                        a++;
                        b = 0;
                    }
                }
            }

            List<String> results = new ArrayList<>();

            for(int i = 0; i < tablesWithTitles.size(); i++) {
                String result = "表" + (i + 1) + "： " + tablesWithTitles.get(i).getText() + "\n";
                boolean haveIssues = false;
                if(tablesWithTitles.get(i) ==  null || tablesWithTitles.get(i).isEmpty()) {
                    haveIssues = true;
                    result += "表格标题应紧跟在表格上方\n";
                }else {
                    if(!tablesWithTitles.get(i).getText().startsWith(correctTableNumbering.get(i))) {
                        haveIssues = true;
                        result += "表格标题应为" + correctTableNumbering.get(i) + "\n";
                    }

                    boolean isSimSun = WordUtils.checkFontFamily(tablesWithTitles.get(i));
                    boolean isSize5 = WordUtils.checkFontSize(tablesWithTitles.get(i));
                    boolean isCentered = WordUtils.checkAlignment(tablesWithTitles.get(i));
                    if (!isSimSun) {
                        haveIssues = true;
                        String res = "字体应为宋体\n";
                        result += res;
                    }
                    if(!isSize5) {
                        haveIssues = true;
                        String res = "字体大小应为五号\n";
                        result += res;
                    }
                    if (!isCentered) {
                        haveIssues = true;
                        String res = "段落应居中\n";
                        result += res;
                    }
                }
                if (!haveIssues) {
                    String res = "表格标题正确\n";
                    result += res;
                }
                results.add(result);
            }
            return results;
        }catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private List<String> getTableTitles(XWPFDocument doc) throws IOException {
        List<String> headings = WordUtils.findHeadingOne(doc);
        List<String> titles = new ArrayList<>();
        List<IBodyElement> bodyElements = doc.getBodyElements();
        // 遍历所有元素
        for (int i = 0; i < bodyElements.size(); i++) {
            IBodyElement element = bodyElements.get(i);

            // 如果当前元素是表格
            if (element instanceof XWPFTable) {
                // 回溯查找表名
                if(i > 0) {
                    XWPFParagraph para = (XWPFParagraph) bodyElements.get(i - 1);
                    titles.add(para.getText().trim());
                }
            }else if (element instanceof XWPFParagraph) {
                String text = ((XWPFParagraph) element).getText();
                if(headings.contains(text.trim())) {
                }
            }
        }
        return titles;
    }

    private List<String> getTableContent(XWPFDocument doc) throws IOException {
        List<XWPFTable>  tables = doc.getTables();
        List<String> contents = new ArrayList<>();
        for(XWPFTable table : tables) {
            contents.add(table.getText());
        }
        return contents;
    }

    @Override
    public List<String> checkTableContent(XWPFDocument doc) throws IOException {
        List<String> results = new ArrayList<>();

        List<String> tableTitles =  getTableTitles(doc);
        List<String> tables =  getTableContent(doc);

        for(int i = 0; i < tableTitles.size(); i++) {
            Map<String, String> resMap = JSONObject.toJavaObject(JSON.parseObject(tableAiCheck(tableTitles.get(i), tables.get(i))), Map.class);
            results.add("表格" + (i + 1) + "\n" + tableTitles.get(i) + "\n" +  resMap.get("cod").toString() + "\n" + resMap.get("reason") + "\n" + resMap.get("suggest") + "\n");
        }

        return results;
    }

    private String tableAiCheck(String tableTitle, String tableContent) {
        String text = "表格标题：\n" + tableTitle + "\n表格内容：\n";
        text +=  tableContent + "\n";
        String question = "判断表格标题与内容是否相符";
        HashMap<String, Object> format = new HashMap<>();
        format.put("cod", "图片与标题是否相符,回答为‘是’或‘否’");
        format.put("reason", "原因");
        format.put("suggest", "修改建议");

        SparkClient sparkClient = new SparkClient();
        sparkClient.setModel("spark-max");
        sparkClient.setFormat(format);

        return sparkClient.processRequest(question, text).get("answer").toString();
    }
}
